package logic

import (
	"C/renrenzhuC_srv/model/Es"
	"bytes"
	"context"
	"encoding/json"
	"log"

	"C/renrenzhuC_srv/internal/svc"
	"C/renrenzhuC_srv/renrenzhuC"

	"github.com/zeromicro/go-zero/core/logx"
)

type EsGetLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewEsGetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EsGetLogic {
	return &EsGetLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *EsGetLogic) EsGet(in *renrenzhuC.EsGetRequest) (*renrenzhuC.EsGetResponse, error) {
	// todo: add your logic here and delete this line

	var buf bytes.Buffer
	query := map[string]interface{}{}
	if in.Keyword == "" {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match_all": map[string]interface{}{},
			},
		}
	} else {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					"title": in.Keyword,
				},
			},
		}
	}

	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}

	// Perform the search request.
	res, err := Es.Es.Search(
		Es.Es.Search.WithContext(context.Background()),
		Es.Es.Search.WithIndex("goods"),
		Es.Es.Search.WithBody(&buf),
		Es.Es.Search.WithTrackTotalHits(true),
		Es.Es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()

	r := map[string]interface{}{}
	json.NewDecoder(res.Body).Decode(&r)

	var good []*renrenzhuC.GoodsList

	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		Source := hit.(map[string]interface{})["_source"].(map[string]interface{})

		goods := renrenzhuC.GoodsList{
			Title:  Source["Title"].(string),
			Price:  float32(Source["Price"].(float64)),
			Cover:  Source["Cover"].(string),
			Stock:  Source["Stock"].(int64),
			Status: Source["Status"].(string),
			Likes:  Source["Likes"].(int64),
			Type:   Source["Type"].(string),
		}

		good = append(good, &goods)
	}

	return &renrenzhuC.EsGetResponse{List: good}, nil
}
